﻿using System.Linq;
using System.Web.Mvc;
using OpenMVCRM.DataAccess;
using OpenMVCRM.Entities;
using OpenMVCRM.Mapping;
using OpenMVCRM.ViewModels;

namespace OpenMVCRM.Controllers
{
    public class ContactController : BaseController
    {
        private IRepositary repo;
        public ContactController()
        {
            repo = new Repositary();
        }
        public ActionResult Index()
        {

            var res = repo.GetContactPersons(GetCurrentOrgID()).ToList();
            var contactPersonVMList = PersonService.GetContactPersonVMList(res);
            return View(contactPersonVMList);
        }

        public ActionResult Create()
        {
            ContactPersonViewModel contactVM = new ContactPersonViewModel();
            return View(contactVM);
        }

        [HttpPost]
        public ActionResult Create(ContactPersonViewModel model)
        {
            if (ModelState.IsValid)
            {
                var contactEntity = new ContactPerson();
                contactEntity.FirstName = model.FirstName;
                contactEntity.LastName = model.LastName;
                contactEntity.EmailAddress = model.EmailAddress;
                contactEntity.HomePhone = model.HomePhone;
                contactEntity.MobilePhone = model.MobilePhone;


                contactEntity.Organization = new Company();

                contactEntity.Organization.ID = model.ParentOrganizationID;

                if (model.ParentOrganizationID == 0)  // New Organization. Let's save that.
                {
                    contactEntity.Organization.Name = model.ParentOrganizationName;
                    //repo.SaveClient(contactEntity.Organization);
                }



                var result = repo.InsertContactPerson(contactEntity);
                if (result.Status)
                {
                    return RedirectToAction("View", new { @id = result.OperationID, @m = "c" });
                }
                else
                {
                    // TO DO : log error
                }

            }
            return View(model);
        }

        public ActionResult View(int id, string m = "")
        {
            return View();
        }

        public string nullToString(string value)
        {
            return value == null ? string.Empty : value;
        }
    }
}